/*
Copyright (C) 2012 Brady Vidovic

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ftr.tools;

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;
import static btv.tools.BTVConstants.*;

/**
 * Starts execution of a batch file and return immediately.
 * Passed recordingPath as single argument to the bat file
 * @author Brady Vidovic
 */
public class PostProcessStarter implements Runnable{
    
    private String batFilePath, recordingPath;
    private Thread t;
    public PostProcessStarter(String batFilePath, String recordingPath){
        this.batFilePath = batFilePath;
        this.recordingPath = recordingPath;
        this.t = new Thread(this);
        execute();
    }
    private void execute(){        
        t.start();      
    }

    @Override
    public void run() {
        
        try 
        {
            ProcessBuilder pb = new ProcessBuilder(batFilePath, recordingPath);    
            pb.redirectErrorStream(true);
            
            Process p = pb.start();
            
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null; 
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            
            
            //Thread.sleep(1000);//give it a second to start up                        
            int exitCode = p.waitFor();//TODO: check this
            Logger.INFO("Post-Process exited with code "+ exitCode +": "+batFilePath+" " + recordingPath);
            
        } catch (Exception ex) {
            Logger.ERROR("Failed to init post-processing batch file: "+ batFilePath +" for file: \""+recordingPath+"\"");
        }
    }
    
}
